﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ciloci.Flee;
using System.Text.RegularExpressions;

namespace fleeEval
{
    class language
    {
        private string expression;
        private ExpressionContext context;
        public int i;
        private string[] split;

        public language()
        {
            this.expression = "";
        }

        public language(ref ExpressionContext cont)
        {
            this.expression = "";
            this.context = cont;
        }

        public void getexp(string exp)
        {
            this.expression = exp;
        }

        //the output function, uses regex to find the $ delimited substrings and calls the replace method to replace them with variables
        public void print(string exp, ref ExpressionContext cont)
        {
            this.context = cont;
            this.expression = exp;
            MatchEvaluator eval = new MatchEvaluator(this.matchEval);
            exp = Regex.Replace(exp, @"(?<!\w)\$\w+", eval);
            Console.WriteLine(exp);
        }

        //custom match evaluator, 
        private string matchEval(Match m)
        {
            string Return = m.ToString();
            Return = Return.Trim('$');
            return this.context.Variables[Return].ToString();
        }

        public void getVar(string varName, ref ExpressionContext cont)
        {
            this.context = cont;
            string tempVar = Console.ReadLine();
            var castedVar = this.checkType(tempVar);
            if (!this.context.Variables.ContainsKey(varName))
            {
                this.context.Variables.Add(varName, castedVar);
            }
            else
            {
                this.context.Variables.Remove(varName);
                this.context.Variables.Add(varName, castedVar);
            }
        }

        //another checktype method, was too lazy to do a little modifying, so i copy-pasta the one in parser.cs into here.
        private object checkType(string item)
        {
            try
            {
                return int.Parse(item);
            }
            catch
            {
                try
                {
                    return float.Parse(item);
                }
                catch
                {
                    try
                    {
                        return bool.Parse(item);
                    }
                    catch
                    {
                        return item;
                    }
                }
            }
        }
    }
}
